#include <p24fj16ga002.h>
#include "Config.h"
#include "1wire.h"
#include "uart.h"

	void init(void){

	   AD1PCFG = 0xffff; //disabilita AN
	   // initialize IO pin mappings	
	   RPOR7bits.RP15R = 18; // OC1 on RP15	
	   RPINR18bits.U1RXR = 10; // UART1 RX on RP10	
	   RPOR5bits.RP11R = 3; // UART1 TX on RP11
	   OSCCONbits.IOLOCK = 1;

	   uart1_init(415, 0x06, 0x05);
	   	// start system timer - 1 ms resolution
	IFS0bits.T1IF = 0;
	IEC0bits.T1IE = 1;
	IPC0bits.T1IP = 0x07;
	T1CONbits.TCKPS1 = 1;
	T1CONbits.TCKPS0 = 0;
	T1CONbits.TCS=0;
	PR1 = 25000-1;
	T1CONbits.TON = 1;
	
		// FIXME Set directions of UART IOs
	TRISBbits.TRISB3 = 0;
	TRISBbits.TRISB2 = 1;

	// Set Baudrate for SysClk
	U1BRG = 415;
	// Set Low Baudrate, No Parity, 1 Stopbit, then enable UART
	U1MODE = 0;
	U1MODEbits.UARTEN = 1;

	// Set default Status, then enable Transmit
	U1STA = 0;
	U1STAbits.UTXEN = 1;

	// reset RX flag
	IFS0bits.U1RXIF = 0;

	// Interrupt enabled
	IEC0bits.U1TXIE = 0;		// Activated by the driver itself
	IEC0bits.U1RXIE = 1;

	// Interrupt priority
	IPC3bits.U1TXIP = 5;
	IPC2bits.U1RXIP = 5;

	AD1PCFGbits.PCFG9 = 1;
	TRISBbits.TRISB0= 1;
	
	
	}
		
		
void uart1_init(unsigned int baud, char rx_priority, char tx_priority)
{
	
	IPC2bits.U1RXIP = rx_priority;
	IPC3bits.U1TXIP = tx_priority;
	IEC0bits.U1RXIE = 1;
	IEC0bits.U1TXIE = 1;
	U1STAbits.UTXISEL0 = 1;
	U1BRG = baud;
	U1MODEbits.BRGH = 1;
	U1MODEbits.UARTEN = 1;
	U1STAbits.UTXEN = 1;
}

